package com.example.aicloud.config;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.example.aicloud.entity.SecurityUserDetails;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 登录认证过滤器
 */

@Component
public class LoginAuthenticationFilter extends OncePerRequestFilter {
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1. 获取 JWT 令牌
        String token = request.getHeader("Authorization");
        //2 判断 JWT 令牌是否为空
        if (StringUtils.hasLength(token)){
            //3. 如果不为空，验证令牌是否正确
            if (JWTUtil.verify(token,jwtSecret.getBytes())){
                //4.获取用户信息存储到 Security中
                JWT jwt = JWTUtil.parseToken(token);
                if (jwt!=null && jwt.getPayload("uid")!=null){
                    Long uid =  Long.parseLong(jwt.getPayload("uid").toString());
                    String username = (String)jwt.getPayload("username");
                    // 创建用户对象
                    SecurityUserDetails userDetails = new SecurityUserDetails(uid,username,"");
                    // 存储到 Security框架中
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); //将userDetails 对象与 request对象进行绑定
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(request,response);
    }
}
